package com.cotasul.converter;

import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.ConverterException;
import javax.faces.convert.FacesConverter;

import com.cotasul.bean.CompradorBean;
import com.cotasul.negocio.CompradorServico;

@FacesConverter(forClass = CompradorBean.class, value = "compradorConverter")
public class CompradorConverter implements Converter {
	private CompradorServico<CompradorBean> compradorServico;
	public CompradorConverter() {
		compradorServico = new CompradorServico<CompradorBean>();
	}
	public Object getAsObject(FacesContext facesContext, UIComponent component,
			String submittedValue) {
		if (submittedValue.trim().equals("")) {
			return null;
		} else {
			try {
				long number = Long.parseLong(submittedValue);
				return (compradorServico.filtraCompradores(new CompradorBean(null, number))).get(0);

			} catch (Exception exception) {
				exception.printStackTrace();
				throw new ConverterException(new FacesMessage(
						FacesMessage.SEVERITY_ERROR, "Erro de Conversão",
						"Não válido"));
			}
		}
	}

	public String getAsString(FacesContext facesContext, UIComponent component,
			Object value) {
		if (value == null || value.equals("")) {
			return "";
		} else {
			return String.valueOf(((CompradorBean) value).getCodigo());
		}
	}
}
